﻿module Tww.Pixxler.BitmapUtils

  open System
  open System.Drawing
  open Tww.Pixxler.ColorTypes
  
  // Konvertiert ein Bitmap in ein 2D Array
  let ToArray2D(bmp:Bitmap) : SimpleColor[,] =
      let rect = Rectangle(0, 0, bmp.Width, bmp.Height) 
      // Lock Bitmap um manipulationen zuzulassen
      let bmpData = bmp.LockBits(rect, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format32bppArgb)
      
      // Bits kopieren
      let ptr0 = bmpData.Scan0 : IntPtr
      let stride = bmpData.Stride
      let res = Array2D.init bmp.Width bmp.Height (fun i j ->
        let offset = i*4 + stride*j
        let clr = Color.FromArgb(System.Runtime.InteropServices.Marshal.ReadInt32(ptr0,offset))
        SimpleColor(int clr.R, int clr.G, int clr.B))
      bmp.UnlockBits(bmpData)
      res 
      
  // Konvertiert ein Array in einen .NET Bitmap Typ
  let ToBitmap(arr:SimpleColor[,]) =
      let bmp = new Bitmap(arr.GetLength(0), arr.GetLength(1))
      let rect = new Rectangle(0, 0, bmp.Width, bmp.Height)
      // Lock Bitmap um manipulationen zuzulassen
      let bmpData = bmp.LockBits(rect, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format32bppArgb)
      
      // Bits kopieren
      let ptr0 = bmpData.Scan0 : IntPtr
      let stride = bmpData.Stride
      for i = 0 to bmp.Width - 1 do
        for j = 0 to bmp.Height - 1 do
          let offset = i*4 + stride*j
          let clr = arr.[i,j]
          let clr = Color.FromArgb(clr.R, clr.G, clr.B).ToArgb()
          System.Runtime.InteropServices.Marshal.WriteInt32(ptr0, offset, clr)
      bmp.UnlockBits(bmpData)
      bmp




